package com.application.admin;

import com.alibaba.fastjson.JSON;
import com.application.common.utils.ExportUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller("/admin/export")
public class ExportController extends BaseController {

    public void index() {
        String type = getPara("type");
        String s = "";
        List<Record> list = new ArrayList<>();
        switch (type) {
            case "property":
                String pkg = "com.application.property.splitPage";
                s = getSqlByBeetl(pkg + "Select", new HashMap<>()) + getSqlByBeetl(pkg + "From", new HashMap<>());
                list = Db.find(s);
                break;
            case "department":
                s = "SELECT a.*, b.names as parentname\n" +
                        "from pt_department a left join pt_department b on a.parentdepartmentids = b.ids\n" +
                        "order by a.parentdepartmentids, orderids";
                list = Db.find(s);
                break;
            case "unmark":
                Map<String, Object> map = new HashMap<>();
                map.put("time1", getPara("time1"));
                map.put("time2", getPara("time2"));
                map.put("status", getPara("status"));
                s = getSqlByBeetl("app.map.getUnmarkOrderList", map);
                list = Db.find(s);
                for (Record r : list) {
                    String d = r.get("detail");
                    String p = r.get("pname");
                    String c = r.get("cname");
                    if(p != null && c != null) {
                        String str = p + c;
                        if(!d.startsWith(str)) {
                            r.set("detail", str + d);
                        }
                    }
                }
                break;
        }

        render(ExportUtil.exportSingle(type, list));
    }

    public void enterpriseDetail() {
        String qW = getSqlWhere();
        long start = System.currentTimeMillis();
        String sql = "select t.ids,t.name,address,scale,license,licensetime,updatetime,buildtime,opentime," +
                " mastername,mastertel, b.name as categoryName" +
                " from enterprise t left join category b on t.categoryid = b.ids where t.status = 1 " + qW +
                " order by t.createtime desc";

        //基础数据列表
        String s1 = "SELECT a.enterpriseid, b.key, a.value, b.type, b.field from basic_item a  \n" +
                " left join basic_template_item b on a.basic_template_item_id = b.ids\n" +
                " left join enterprise t on t.ids = a.enterpriseid " +
                " where b.field is not NULL and field != '' " + qW;

        String s2 = "SELECT a.enterpriseid, b.value,b.type, c.field from inspect a \n" +
                "left join inspect_item b on a.ids = b.inspectid\n" +
                "left join inspect_template_item c on b.inspect_template_item_id = c.ids\n" +
                " left join enterprise t on t.ids = a.enterpriseid " +
                "where not EXISTS (\n" +
                "SELECT 1 from inspect b where a.enterpriseid = b.enterpriseid and b.createtime > a.createtime\n" +
                ")\n" +
                "and a.createtime is not null\n" +
                "and field is not null and field != '' " + qW;


        //查询企业列表，设置map
        List<Record> enterpriseList = Db.find(sql);
        long t1 = System.currentTimeMillis();
        Map<String, Record> epMap = new HashMap<>();
        for (int i = 0; i < enterpriseList.size(); i++) {
            Record ep = enterpriseList.get(i);
            ep.set("num", i + 1);
            epMap.put(ep.getStr("ids"), ep);
        }

        //封装基础数据
        List<Record> itemList = Db.find(s1);
        long t2 = System.currentTimeMillis();
        itemList.forEach(item -> {
            String value = item.getStr("value");
            epMap.get(item.getStr("enterpriseid")).set(item.getStr("field"), getJsonKey(value));
        });

        long time2 = System.currentTimeMillis();

        //封装巡查数据
        itemList = Db.find(s2);
        long t3 = System.currentTimeMillis();
        itemList.forEach(item -> {
            String value = item.getStr("value");
            epMap.get(item.getStr("enterpriseid")).set(item.getStr("field"), getJsonKey(value));
        });


        long time3 = System.currentTimeMillis();

        System.out.println("#########query list cost: " + (t1 - start) + "ms");
        System.out.println("#########query s1 cost: " + (t2 - t1) + "ms");
        System.out.println("#########set basic cost: " + (time2 - t2) + "ms");
        System.out.println("#########query s2 cost: " + (t3 - time2) + "ms");
        System.out.println("#########set inspect cost: " + (time3 - t3) + "ms");

        render(ExportUtil.exportSingle("enterpriseDetail", enterpriseList));
    }

    private String getSqlWhere() {
        String s = "";
        Map<String, String> param = getQueryParam();
        String area = param.get("areaid");
        String street = param.get("streetid");
        String property = param.get("propertyid");
        String q = param.get("keyword");

        if (!StrKit.isBlank(area)) {
            s += " and areaid = '" + StringEscapeUtils.escapeSql(area) + "'";
        }
        if (!StrKit.isBlank(street)) {
            s += " and streetid = '" + StringEscapeUtils.escapeSql(street) + "'";
        }
        if (!StrKit.isBlank(property)) {
            s += " and propertyid = '" + StringEscapeUtils.escapeSql(property) + "'";
        }
        if (!StrKit.isBlank(q)) {
            try {
                q = new String(q.getBytes("ISO8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            s += " and instr(t.name, '" + StringEscapeUtils.escapeSql(q) + "') > 0";
        }

        return s;
    }

    /*
    解析json，获取其中选中的值
     */
    private String getJsonKey(String value) {
        String val = "";
        if (value != null) {
            value = value.replaceAll("\\s*", "").trim();
            if (value.startsWith("[")) {
                List<Map<String, String>> mapList = (List<Map<String, String>>) JSON.parse(value);
                for (Map<String, String> map : mapList) {
                    if ("1".equals(String.valueOf(map.get("value")))) {
                        if (val.length() > 0) {
                            val += "、" + map.get("key");
                        } else {
                            val = map.get("key");
                        }
                    }
                }
            } else {//其他类型
                val = value;
            }
        }
        return val;
    }

}
